const express = require('express');
const cors = require('cors');
const Nls = require('alibabacloud-nls');
const app = express();

// 阿里云配置
const config = {
    accessKeyId: '79a31393d2dc4cb39d749c8931e1aa21',
    accessKeySecret: 'YOUR_ACCESS_KEY_SECRET', // 这个值可以留空，因为我们使用固定的Token
    appKey: '7eVPKoZTnKR9z1GX'
};

// 验证配置
if (config.accessKeyId === 'YOUR_ACCESS_KEY_ID' || 
    config.accessKeySecret === 'YOUR_ACCESS_KEY_SECRET' || 
    config.appKey === 'YOUR_APP_KEY') {
    console.error('请配置阿里云访问密钥！');
    console.error('可以通过环境变量设置：');
    console.error('ALIYUN_ACCESS_KEY_ID');
    console.error('ALIYUN_ACCESS_KEY_SECRET');
    console.error('ALIYUN_APP_KEY');
    process.exit(1);
}

app.use(cors());
app.use(express.json());

// 创建语音识别实例
const speechTranscription = new Nls.SpeechTranscription({
    url: 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1',
    appkey: config.appKey
});

// 设置事件监听
speechTranscription.on('started', (msg) => {
    console.log('识别开始:', msg);
});

speechTranscription.on('changed', (msg) => {
    console.log('识别中间结果:', msg);
});

speechTranscription.on('completed', (msg) => {
    console.log('识别完成:', msg);
});

speechTranscription.on('failed', (msg) => {
    console.error('识别失败:', msg);
});

// Token接口
app.get('/token', async (req, res) => {
    try {
        // 直接返回固定的Token信息
        res.json({
            token: '79a31393d2dc4cb39d749c8931e1aa21',
            appkey: config.appKey,
            url: 'wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1'
        });
    } catch (error) {
        console.error('获取Token失败:', error);
        res.status(500).json({ error: '获取Token失败' });
    }
});

// 测试接口
app.get('/test', async (req, res) => {
    try {
        // 开始识别
        await speechTranscription.start(speechTranscription.defaultStartParams(), true, 6000);
        
        // 发送测试音频数据
        const testBuffer = Buffer.from('test audio data');
        speechTranscription.sendAudio(testBuffer);
        
        // 关闭识别
        await speechTranscription.close();
        
        res.json({ message: '测试成功' });
    } catch (error) {
        console.error('测试失败:', error);
        res.status(500).json({ error: '测试失败' });
    }
});

const PORT = 9527;
app.listen(PORT, () => {
    console.log(`Token服务器运行在 http://172.20.10.6:${PORT}`);
}); 